#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "report_data.h"
#include "msg_queue.h"

MsgQueue msg_queue;
time_t last_sending_time;

void init_report_data() {
    init_MsgQueue(&msg_queue);
    time(&last_sending_time);
}

void end_report_data() {
    destroy_MsgQueue(&msg_queue);
}

void build_report(ReportData* report, int data_num) {
    if (msg_queue.size < data_num) {
        return;
    }
    report->data_len = data_num;
    report->gateway_id = GATEWAY_ID;
    report->data = (WrappedData*)malloc(sizeof(WrappedData) * data_num);
    for (int i = 0; i < data_num; ++i) {
        report->data[i] = *head_MsgQueue(&msg_queue);
        pop_MsgQueue(&msg_queue);
    }
}

void destroy_report(ReportData* report) {
    free(report->data);
}

void print_report(const ReportData* report) {
    printf("=== report data ===\n");
    printf("gateway id: %d\n", report->gateway_id);
    printf("data len: %d\n", report->data_len);
    for (int i = 0; i < report->data_len; ++i) {
        print_wrapped_data(&report->data[i]);
    }
    printf("=== end report data ===\n");
}

void send_report(const ReportData* report) {
    print_report(report);
    time(&last_sending_time);
}

void on_report_receive_data(WrappedData* data) {
    push_MsgQueue(&msg_queue, data);
    if (msg_queue.size > MAX_RPT_LEN) {
        ReportData report;
        build_report(&report, MAX_RPT_LEN);
        send_report(&report);
        destroy_report(&report);
    }
}

void on_loop_sending_report() {
    time_t current_time;
    time(&current_time);
    if (current_time - last_sending_time > MAX_SENDING_INTEVAL && msg_queue.size > 0) {
        ReportData report;
        build_report(&report, msg_queue.size);
        send_report(&report);
        destroy_report(&report);
    }
}